//
//  RAPTextView.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/5/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

//private let kUpperMagin: CGFloat = 4
//private let kLeadingMargin: CGFloat = 8

class RAPTextView: UITextView, UITextViewDelegate {
    
    // MARK: - 自定义属性
    /// 文字改变的回调
    var textViewChangedClosure: ((textView: UITextView) -> ())?
    
    var beginDragginClosure: ((textView: UITextView) -> ())?
    
    var placeholderText: String? {
        didSet {
            guard let opPlaceholderText = placeholderText else {
                return
            }
            
            let size = (opPlaceholderText as NSString).boundingRectWithSize(CGSizeMake(kScreenBounds.width - 10, CGFloat.max), options: [.UsesLineFragmentOrigin], attributes: [NSFontAttributeName : placeholderLabel.font], context: nil).size
            placeholderLabel.frame.size = size
            placeholderLabel.text = opPlaceholderText
            
            // 添加占位label
            addSubview(placeholderLabel)
            
        }
    }
    
    // MARK: - 系统方法
    /**
    注意，只能通过init()创建RAPTextView，然后给其添加约束
    而非init(frame)
    */
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareForUse()
    }
    
    private func prepareForUse() {
        backgroundColor = UIColor.whiteColor()
        // 调整键盘弹出模式
//        keyboardDismissMode = .OnDrag
        self.delegate = self
        showsVerticalScrollIndicator = false
        // 这个属性必须设置，才可以在不够长的情况下上下拖动
        alwaysBounceVertical = true
        
        // 接收自身通知，将占位label隐藏
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var font: UIFont? {
        didSet {
            /*
            如果调整了text view的字体，占位文字的字体也将得到调整
            */
            placeholderLabel.font = font
            
        }
    }
    
    /*
    重写attributedText，设置这个值之后，立即隐藏占位label，
    同时调用代理方法，告知代理内部文字已经改变
    */
    override var attributedText: NSAttributedString! {
        didSet {
            placeholderLabel.hidden = true
            self.delegate?.textViewDidChange?(self)
        }
    }
    
    // MARK: - 动作方法
    @objc private func textDidChange() {
        if self.hasText() {
            placeholderLabel.hidden = true
        } else {
            placeholderLabel.hidden = false
            
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var  placeholderLabel: UILabel = {
        let placeholderLabel = UILabel(text:self.placeholderText, fontSize: 12, textColor: UIColor.lightGrayColor())
        
        placeholderLabel.numberOfLines = 0
        /*
        注意，12号字体与8的切合度最好，
        由于暂时无法获取控件的字号，
        还不能动态调整占位label的位置
        */
        placeholderLabel.frame.origin = CGPointMake(5, 8)
        return placeholderLabel
    }()
}

// MARK: - UITextViewDelegate
extension RAPTextView {
    func textViewDidChange(textView: UITextView) {
        self.textViewChangedClosure?(textView: textView)
    }
}

// MARK: - UIScrollViewDelegate
extension RAPTextView {
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        RAPLog("即将开始拖动")
        self.beginDragginClosure?(textView: scrollView as! UITextView)
        self.resignFirstResponder()
    }
}
